package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * @projectName: ngsapitask-hst
 * @package: cn.com.kh.hst
 * @className: apiGoogleTranslate
 * @author: LiJT
 * @description: 华盛证券翻译接口-内部部接口
 * @date: 2023-09-27 11:50
 * @version: 1.0
 */
public class api_GoogleTranslate implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(api_GoogleTranslate.class);

    private static String transURL = "https://translation.googleapis.com/language/translate/v2";
    //private static String apiKey = "AIzaSyAACAMsBWCxiElkIKFvf5T28IP9B7dsWi8";
    private static String apiKey = "f51a40e4d9e588b4745724b37833da05ed126703";

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        // 返回数据及示例
        JSONObject reJson = new JSONObject();
        JSONArray trans_result = new JSONArray();

        //获取参数js_code，登录时获取的 code
        String q = request.getParameter("q");
        String from = request.getParameter("from");
        String to = request.getParameter("to");

        // 语言转码(Chat默认按百度语言字典Google需要转码)
        from = from == "cht" ? "zh-HK" : from == "zh" ? "zh-CN" : from;
        to = to == "cht" ? "zh-HK" : to == "zh" ? "zh-CN" : to;

        // 转义待翻译内容
        String qText = null;
        try {
            qText = URLDecoder.decode(q, "UTF-8");
        } catch (Exception e) {
            log.warn("转义待翻译内容错误：" + e.getMessage());
            qText = q;
        }
        log.debug("接收参数qText：" + q + " from：" + from + " to：" + to + " 转义qText：" + qText);

        try {
            // 调用Google翻译
            JSONObject transObject = getTranslate(qText, from, to);

            // 解析Google翻译
            if (transObject.getInt("code") == 0) {
                // 翻译结果成功
                JSONArray translations = transObject.getJSONObject("data").getJSONArray("translations");
                for (int i = 0; i < translations.size(); i++) {
                    JSONObject transObj = new JSONObject();
                    transObj.put("src", qText);
                    transObj.put("dst", translations.getJSONObject(i).getString("translatedText"));
                    trans_result.add(transObj);
                }
                reJson.put("trans_result", trans_result);
                reJson.put("trans_message", transObject.getString("message"));
                reJson.put("trans_data", transObject.getJSONObject("data"));
            } else {
                // 翻译结果异常
                JSONObject transObj = new JSONObject();
                transObj.put("src", qText);
                transObj.put("dst", qText);
                trans_result.add(transObj);
                reJson.put("trans_result", trans_result);
                reJson.put("trans_message", transObject.getString("message"));
                reJson.put("trans_data", transObject.getJSONObject("error"));

            }
            log.debug("解析Google翻译：" + reJson.toString());

            // 处理返回结果
            reJson.put("from", from);
            reJson.put("to", to);
            log.debug("处理后返回Chat结果：" + reJson.toString());

        } catch (Exception e) {
            log.error("接口处理异常", e);
            reJson.put("from", from);
            reJson.put("to", to);

            JSONObject transObj = new JSONObject();
            transObj.put("src", qText);
            transObj.put("dst", qText);
            trans_result.add(transObj);
            reJson.put("trans_result", trans_result);
            reJson.put("trans_message", e.getMessage());
        }
        log.debug("翻译处理结果：" + reJson.toString());
        return reJson.toString();

    }

    // 调用Google翻译
    public static JSONObject getTranslate(String text, String sourceLang, String targetLang) {

        log.debug("调用Google翻译入参信息-sourceLang:" + sourceLang + " targetLang:" + targetLang + " text:" + text);
        JSONObject resTrans = new JSONObject();

        Map<String, String> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/x-www-form-urlencoded");

        Map<String, String> params = new HashMap<>();
        params.put("q", text);
        params.put("source", sourceLang);
        params.put("target", targetLang);

        params.put("key", apiKey);

        try {
            log.debug("调用Google翻译返回信息-input:" + getMapToForm(params));
            String output = Util.doHttpPostUseHead(transURL, getMapToForm(params), "UTF-8", 5000, 0, headMap);
            log.debug("调用Google翻译返回信息-output:" + output);

            // 解析处理返回结果
            resTrans = JSONObject.fromObject(output);
            if (resTrans.has("error")) {
                // 调用异常
                resTrans.put("code", resTrans.getJSONObject("error").getInt("code"));
                resTrans.put("message", resTrans.getJSONObject("error").getString("message"));
            } else {
                // 调用成功
                resTrans.put("code", 0);
                resTrans.put("message", "调用成功");

            }
        } catch (Exception e) {
            log.error("调用Google翻译接口处理异常", e);
            resTrans.put("code", -1);
            resTrans.put("message", "调用Google翻译调用异常:" + e.getMessage());
        }

        log.debug("调用Google翻译返回信息-最终结果:" + resTrans);
        return resTrans;
    }

    /**
     * @param params : 入参信息Map
     * @return String
     * @author LiJT
     * @description TODO
     * @date 2023-09-27 15:27
     */
    public static String getMapToForm(Map<String, String> params) {
        if (params == null) {
            return "";
        }

        StringBuilder builder = new StringBuilder();

        int i = 0;
        for (String key : params.keySet()) {
            String value = params.get(key);
            if (value == null) { // 过滤空的key
                continue;
            }

            if (i != 0) {
                builder.append('&');
            }

            builder.append(key);
            builder.append('=');
            builder.append(encode(value));

            i++;
        }

        return builder.toString();
    }

    /**
     * 对输入的字符串进行URL编码, 即转换为%20这种形式
     *
     * @param input 原文
     * @return URL编码. 如果编码失败, 则返回原文
     */
    public static String encode(String input) {
        if (input == null) {
            return "";
        }

        try {
            return URLEncoder.encode(input, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return input;
    }
}